﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace ZoomableCanvasTest {
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window {
        
        public Point LastMousePosition { get; set; }

        public MainWindow() {
            InitializeComponent();
        }

        protected override void OnMouseWheel(MouseWheelEventArgs e) {
            var ratio = Math.Pow(2, e.Delta / 3.0 / Mouse.MouseWheelDeltaForOneLine);

            Vector offset = new Vector(-this._canvas.ActualWidth / 2.0, -this._canvas.ActualHeight / 2.0);
            this._canvas.Scale *= ratio;
            var position = (Vector)e.GetPosition(this);
            this._canvas.Offset += (Vector)(this._canvas.Offset + position) * (ratio - 1.0);

            PrintCanvasInfo();

            base.OnMouseWheel(e);
        }

        protected override void OnMouseMove(MouseEventArgs e) {
            var position = e.GetPosition(this);
            if (e.LeftButton == MouseButtonState.Pressed) {
                _canvas.Offset -= position - LastMousePosition;
            }
            LastMousePosition = position;

            PrintCanvasInfo();

            base.OnMouseMove(e);
        }

        private void PrintCanvasInfo() {
            Point ptCanvas = Mouse.GetPosition(_canvas);    // canvas
            Point ptWindow = Mouse.GetPosition(this);       // this window

            string strInfo = string.Format("Offset: {0:F2},{1:F2}\n", _canvas.Offset.X, _canvas.Offset.Y);
            strInfo += string.Format("Scale: {0:F4}\n", _canvas.Scale);
            strInfo += string.Format("MousePos_Window: {0:0000},{1:0000}\n", ptWindow.X, ptWindow.Y);
            strInfo += string.Format("MousePos_Canvas: {0:F2},{1:F2}\n", ptCanvas.X, ptCanvas.Y);
            strInfo += string.Format("Canvas Size: {0:F2},{1:F2}\n", _canvas.ActualWidth, _canvas.ActualHeight);
            _txtInfo.Text = strInfo;
        }

        private void Window_SizeChanged(object sender, SizeChangedEventArgs e) {
            PrintCanvasInfo();
        }
    }
}
